package com.innovation.ic.im.end.web.thread;

import com.alibaba.fastjson.JSON;
import com.google.common.base.Strings;
import com.innovation.ic.b1b.framework.manager.ThreadPoolManager;
import com.innovation.ic.im.end.base.model.im_erp9.UserGroupMessage;
import com.innovation.ic.im.end.base.pojo.ServiceResult;
import com.innovation.ic.im.end.base.pojo.constant.MessageType;
import com.innovation.ic.im.end.base.pojo.enums.AvailableStatusEnum;
import com.innovation.ic.im.end.base.service.helper.ServiceImplHelper;
import com.innovation.ic.im.end.base.service.im_erp9.RefUserGroupAccountService;
import com.innovation.ic.im.end.base.thread.AbstractThread;
import com.innovation.ic.im.end.base.vo.im_erp9.SendUserGroupMessageVo;
import com.innovation.ic.im.end.base.vo.im_erp9.UserGroupMessageVo;
import com.innovation.ic.im.end.web.endpoint.UserGroupEndpoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import javax.websocket.Session;
import java.util.*;

/**
 * 群组聊天环境下，将记录消息保存到user_group_message表中
 */
public class SaveUserGroupMessageThread extends AbstractThread implements Runnable {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private String exchange;

    private String urlPrefix;

    private List<String> onlineAccountList;

    private Map<String, Set<UserGroupEndpoint>> onlineUserGroupMap;

    public SaveUserGroupMessageThread() {}

    public SaveUserGroupMessageThread(UserGroupMessage userGroupMessage, UserGroupMessageVo userGroupMessageVo, List<String> onlineAccountList,
                                      String exchange, Map<String, Set<UserGroupEndpoint>> onlineUserGroupMap, ThreadPoolManager threadPoolManager) {
        this.userGroupMessage = userGroupMessage;
        this.userGroupMessageVo = userGroupMessageVo;
        this.onlineAccountList = onlineAccountList;
        this.exchange = exchange;
        this.onlineUserGroupMap = onlineUserGroupMap;
        this.threadPoolManager = threadPoolManager;
    }

    public SaveUserGroupMessageThread(UserGroupMessage userGroupMessage, UserGroupMessageVo userGroupMessageVo, List<String> onlineAccountList,
                                      String exchange, Map<String, Set<UserGroupEndpoint>> onlineUserGroupMap, String urlPrefix, ThreadPoolManager threadPoolManager) {
        this.userGroupMessage = userGroupMessage;
        this.userGroupMessageVo = userGroupMessageVo;
        this.onlineAccountList = onlineAccountList;
        this.exchange = exchange;
        this.urlPrefix = urlPrefix;
        this.onlineUserGroupMap = onlineUserGroupMap;
        this.threadPoolManager = threadPoolManager;
    }

    @Override
    public void run() {
        // 更新最近联系时间
        RefUserGroupAccountService refUserGroupAccountService = ServiceImplHelper.getRefUserGroupAccountService();
        refUserGroupAccountService.updateLastContactTimeByUserGroupId(userGroupMessage.getUserGroupId());

        // 保存自定义群组消息
        userGroupMessage.setFromUserAvailable(AvailableStatusEnum.AVAILABLE.getCode());
        ServiceResult<Integer> integerServiceResult = ServiceImplHelper.getUserGroupMessageService().saveUserGroupMessage(this.userGroupMessage);
        Integer userGroupMsgId = integerServiceResult.getResult();
        userGroupMessageVo.setUserGroupMessageId(userGroupMsgId.toString());

        // 保存自定义群组未读消息
        SaveUserGroupMessageReceiverThread saveUserGroupMessageReceiverThread = new SaveUserGroupMessageReceiverThread(userGroupMessage, userGroupMessageVo, userGroupMsgId, exchange, onlineAccountList);
        threadPoolManager.execute(saveUserGroupMessageReceiverThread);

        // 向自定义群组的所有在线用户推送补充了消息id的数据
        Set<UserGroupEndpoint> userGroupEndpointSet = onlineUserGroupMap.get(userGroupMessageVo.getUserGroupId().toString());
        if(userGroupEndpointSet != null && userGroupEndpointSet.size() > 0){
            for (UserGroupEndpoint userGroupEndpoint : userGroupEndpointSet) {
                Session theSession = userGroupEndpoint.session;
                synchronized (theSession) {
                    if (theSession.isOpen()) {
                        if(userGroupMessageVo.getType() != null && userGroupMessageVo.getType().intValue() == MessageType.PICTURE && !Strings.isNullOrEmpty(userGroupMessageVo.getFilePath())){
                            if(!userGroupMessageVo.getFilePath().contains(urlPrefix)){
                                userGroupMessageVo.setFilePath(urlPrefix + userGroupMessageVo.getFilePath());
                            }
                        }
                        SendUserGroupMessageVo sendUserGroupMessageVo = new SendUserGroupMessageVo();
                        BeanUtils.copyProperties(userGroupMessageVo, sendUserGroupMessageVo);
                        logger.info("sendUserGroupMessageVo=[{}]", sendUserGroupMessageVo);
                        theSession.getAsyncRemote().sendText(JSON.toJSONString(sendUserGroupMessageVo));
                    }
                }

                if(userGroupMessageVo.getType() != null && userGroupMessageVo.getType().intValue() == MessageType.TEXT){
                    logger.info("用户【" + userGroupMessageVo.getFromUserAccount() + "】向自定义群组【"
                            + userGroupMessageVo.getUserGroupId() + "】中的用户【" + userGroupEndpoint.username
                            + "】发送消息【" + userGroupMessageVo.getContent() + "】");
                }else{
                    logger.info("用户【" + userGroupMessageVo.getFromUserAccount() + "】向用户自定义群组【"
                            + userGroupMessageVo.getUserGroupId() + "】中的用户【" + userGroupEndpoint.username
                            + "】发送图片/文件【" + userGroupMessageVo.getFilePath() + "】");
                }
            }
        }
    }
}